package com.bite.springtrans.demos.controller;

import com.bite.springtrans.demos.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;


    @RequestMapping("/registry")
    public String registry(String userName,String password) {
        //用户注册

        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        Integer result = userService.registryUser(userName, password);
        log.info("用户插入成功,result : " + result);

        //回滚事务  意思就是这个操作不会执行成功
        //dataSourceTransactionManager.rollback(transaction);

        //提交事务 会出现 commit
        dataSourceTransactionManager.commit(transaction);
        return "注册成功";
    }
}
